package com.yun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.reggie.common.R;
import com.yun.reggie.dto.DishDto;
import com.yun.reggie.dto.SetmealDto;
import com.yun.reggie.entity.Dish;
import com.yun.reggie.entity.DishFlavor;
import com.yun.reggie.entity.Setmeal;
import com.yun.reggie.entity.SetmealDish;
import com.yun.reggie.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author xiao
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;
    /**
     * 保存套餐setmeal，包括保存套餐-菜品setmealdish
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",key = "#setmealDto.categoryId+'_'+1")
    @PostMapping
    @ApiOperation(value = "新增套餐接口")
    public R<String> add(@RequestBody SetmealDto setmealDto){
        log.error(setmealDto.toString());
        setmealService.addWithDish(setmealDto);
        return R.success("添加成功！");
    }

    @GetMapping("/page")
    @ApiOperation(value = "套餐分页接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "页面记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R<Page<SetmealDto>> page(int page,int pageSize,String name){
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(name),Setmeal::getName,name)
                .orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,wrapper);
        //将Setmeal的分页基本信息复制到SetmealDto中
        BeanUtils.copyProperties(pageInfo,setmealDtoPage);
        //每个SetmealDto还需要携带套餐分类名，根据categoryId查
        List<Setmeal> setmeals = pageInfo.getRecords();
        List<SetmealDto> setmealDtos = new ArrayList<>();
        for (Setmeal setmeal:setmeals) {
            String categoryName = categoryService.getById(setmeal.getCategoryId()).getName();
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal,setmealDto);
            setmealDto.setCategoryName(categoryName);
            setmealDtos.add(setmealDto);
        }
        setmealDtoPage.setRecords(setmealDtos);
        return R.success(setmealDtoPage);
    }

    /**
     * 根据套餐ids批量删除套餐，还需要删除套餐-菜品
     * @RequestParam 将请求参数绑定到你控制器的方法参数上（是springmvc中接收普通参数的注解）
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "删除套餐接口")
    public R<String> delete(@RequestParam List<Long> ids){
        //log.error(ids.toString());
        setmealService.deleteWithDish(ids);
        return R.success("删除成功!");
    }

    /**
     * 根据套餐id，查询套餐信息，套餐-菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个套餐接口")
    public R<SetmealDto> queryById(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.queryByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",key = "#setmealDto.categoryId+'_'+1")
    @PutMapping
    @ApiOperation(value = "修改套餐接口")
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDish(setmealDto);
        return R.success("修改成功！");
    }

    /**
     * 批量停售，起售
     * @param status
     * @param ids 使用List<Long>接收多个数据
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping("/status/{status}")
    @ApiOperation(value = "修改套餐状态接口")
    public R<String> updateStatus(@PathVariable int status,@RequestParam List<Long> ids){
        setmealService.updateWithStatus(ids,status);
        return R.success("修改状态成功！");
    }

    /**
     * 传参方式是键值对，而不是json数据，所以可以直接封装成对象，不能使用@RequestBody
     * http://localhost:8080/setmeal/list?categoryId=1636576325802164226&status=1
     * @param setmeal
     * @return 返回套餐,一个分类中可以有多个套餐
     * 注意：这个处理器方法只是返回套餐的基本信息，对应的菜品信息是由另外的处理器处理
     */
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    @GetMapping("/list")
    @ApiOperation(value = "条件查询套餐列表接口")
    public R<List<Setmeal>> list(Setmeal setmeal){
        //查询套餐，一个分类可以有多个套餐（多个setmeal）
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId())
                .eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus())
                .orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = setmealService.list(setmealWrapper);

        return R.success(setmealList);
    }


    /**
     * 根据套餐id，从套餐-菜品表中查询菜品id,再根据菜品id查询具体的菜品封装成DishDto集合
     * 因为前端需要菜品图片，所以不能使用套餐-菜品表.而且还需要copies菜品份数，所以不能使用Dish
     * @param id
     * @return
     */
    @GetMapping("/dish/{setmealId}")
    @ApiOperation(value = "查询套餐明细接口")
    public R<List<DishDto>> dish(@PathVariable("setmealId") Long id){
        LambdaQueryWrapper<SetmealDish> setmealDishWrapper = new LambdaQueryWrapper<>();
        setmealDishWrapper.eq(SetmealDish::getSetmealId,id);
        //获取套餐-菜品表中套餐对应的菜品id
        List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishWrapper);

        List<DishDto> dishDtoList = new ArrayList<>();
        //根据 套餐-菜品表中 的菜品id，获取具体的菜品,将菜品封装到DishDto集合中
        for (SetmealDish setmealDish:setmealDishList) {
            Dish dish = dishService.getById(setmealDish.getDishId());
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            //给每个DishDto设置份数
            dishDto.setCopies(setmealDish.getCopies());
            dishDtoList.add(dishDto);
        }

        //没有设置口味
        return R.success(dishDtoList);
    }
}
